home *** CD-ROM | disk | FTP | other *** search
- Path: news.nstn.ca!news
- From: keichele@ac.dal.ca (Klaus Eichele)
- Newsgroups: comp.lang.c++
- Subject: Re: Help with float/double data types
- Date: Wed, 31 Jan 1996 04:59:42 GMT
- Organization: Dalhousie University
- Message-ID: <4emev9$pq0@news.nstn.ca>
- References: <96030.105940RWL380B@MAINE.MAINE.EDU>
- NNTP-Posting-Host: rewasylishen.chem.dal.ca
- X-Newsreader: Forte Free Agent 1.0.82
-
- <RWL380B@MAINE.MAINE.EDU> wrote:
-
- >C++ Experts,
-
- >I have a "simple" question re: floating point data types in C/C++.
- >I've traditionally programmed in Fortran but am trying to learn
- >new tricks.... I ran into this problem while trying to write a
- >filter that converts the output of one commercial program to the
- >input format for Arc/Info. A simplified version (just I/O) is
-
- <SNIP>
-
- >If I declare X, Y, Z and Zstd as float:
- > float X=0.0,Y=0.0,Z=0.0,Zstd=0.0;
- >Then the output looks correct but the digits after the decimal points
- >in X are incorrect (original first line X = -2082085.85000). The
- >first value of Y is incorrect, but the next values are correct!
-
- > X-Coordinate Y-Coordinate Z-Est Z StdDev n
- >-2082085.87500 -2127847.00000 23.12121 1.77931 8
-
- <SNIP>
-
- >If I declare X,Y,Z and Zstd to be double then the output is
- >correct.
-
- > X-Coordinate Y-Coordinate Z-Est Z StdDev n
- >-2082085.85000 -2127847.12500 23.12121 1.77931 8
-
- <SNIP>
-
- Hi,
- to give you a hint about what is going on let me first quote the
- comp.lang.c FAQ:
-
- 14.1: When I set a float variable to, say, 3.1, why is printf()
- printing it as 3.0999999?
-
- Most computers use base 2 for floating-point numbers as well as
- for integers. In base 2, 1/1010 (that is, 1/10 decimal) is an
- infinitely-repeating fraction: its binary representation is
- 0.0001100110011... .
- Depending on how carefully your compiler's binary/decimal
- conversion routines (such as those used by printf) have
- been written, you may see discrepancies when numbers (especially
- low-precision floats) not exactly representable in base 2 are
- assigned or read in and then printed (i.e. converted from base 10
- to base 2 and back again).
-
- With floats (usually a 4 byte entity), you will have about 7
- significant digits, and this is where you are running into trouble
- with your output of large numbers. With doubles (in FORTRAN REAL*8),
- you will have approx. 15 significant digits represented properly,
- therefore the output seems to work in this case.
-
- Hope this helps,
- Klaus
- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- Klaus Eichele keichele@ac.dal.ca
- http://ac.dal.ca/~keichele/keichele.html
-
-